package com.mengxiangnongfu.config.shiro;

import com.mengxiangnongfu.constants.Constants;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.context.annotation.Configuration;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.UUID;

/**
 * 判断请求头是否存在token
 * 如果存在token直接从请求头取出token
 * 如果没有token重新生成token
 *
 * @author Yang
 */
@Configuration
public class TokenWebSessionManager extends DefaultWebSessionManager {

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String header = WebUtils.toHttp(request).getHeader(Constants.TOKEN);
        if (StringUtils.hasText(header)) {
            return header;
        }
        //剔除uuid的 '-'
        return UUID.randomUUID().toString().replace("-", "");
    }
}
